package com.ruoyi.business.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.business.domain.FilePerson;
import com.ruoyi.business.domain.vo.FilePersonImportVo;
import com.ruoyi.business.service.IFilePersonService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class FilePersonImportListener extends AnalysisEventListener<FilePersonImportVo> implements ExcelListener<FilePersonImportVo> {

    private final IFilePersonService personService;
    private final ISysDeptService deptService;

    private final Boolean isUpdateSupport;

    private final Map<String, SysDept> importDeptCache;


    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public FilePersonImportListener(Boolean isUpdateSupport) {
        this.deptService = SpringUtils.getBean(ISysDeptService.class);
        this.personService = SpringUtils.getBean(IFilePersonService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.importDeptCache = new HashMap<>();
    }

    @Override
    public void invoke(FilePersonImportVo personVo, AnalysisContext context) {
        FilePerson person = this.personService.selectFilePersonByCode(personVo.getCode());
        boolean isNull = ObjectUtil.isNull(person);
        try {
            person = BeanUtil.toBean(personVo, FilePerson.class);

            if ("男".equals(personVo.getGender())) {
                person.setGender("0");
            } else {
                person.setGender("1");
            }

            String groupName = personVo.getGroupName();

            if (!importDeptCache.containsKey(groupName)) {
                importDeptCache.put(groupName, deptService.selectDeptByName(groupName));
            }
            SysDept org = importDeptCache.get(groupName);
            if (ObjectUtil.isNull(org)) {
                failureNum++;
                failureMsg.append("<br/>").append(personVo.getIndex()).append("、机构名称《 ").append(groupName).append("》不存在");
                return;
            }

            String deptName = personVo.getDeptName();
            if (!importDeptCache.containsKey(deptName)) {
                String[] deptNameSplit = deptName.split(">");
                for (int i = 0; i < deptNameSplit.length; i++) {
                    String name = deptNameSplit[i];
                    SysDept sysDept = deptService.selectDeptByNameInParent(org.getDeptId(), name);
                    if (ObjectUtil.isNull(sysDept)) {
                        failureNum++;
                        failureMsg.append("<br/>").append(personVo.getIndex()).append("、部门名称中《 ").append(name).append("》不存在");
                        return;
                    } else {
                        org = sysDept;
                    }
                }
                importDeptCache.put(deptName, org);
            }

            SysDept dept = importDeptCache.get(deptName);
            person.setOrgid(dept.getDeptId());

            // 验证是否存在这个用户
            if (isNull) {
                personService.insertInFilePerson(person);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(person.getName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                Long personId = person.getId();
                person.setId(personId);
                ValidatorUtils.validate(person);
                personService.updateFilePerson(person);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(person.getName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(person.getName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + person.getName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 此方法在Excel所有数据解析完成后调用，当前业务场景下无需特殊处理
    }

    @Override
    public ExcelResult<FilePersonImportVo> getExcelResult() {
        return new ExcelResult<FilePersonImportVo>() {

            @Override
            public String getAnalysis() throws ServiceException {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<FilePersonImportVo> getList() {
                // 当前业务场景下不需要返回导入数据列表，因此返回null
                return null;
            }

            @Override
            public List<String> getErrorList() {
                // 当前业务场景下不需要返回错误列表，因此返回null
                return null;
            }
        };
    }
}
